const { OrderItem, Order, Product, User, Category } = require("../models");
const { Op } = require("sequelize");
const createError = require("http-errors");

/**
 * 订单项服务类：处理订单项的业务逻辑和联表查询
 */
class OrderItemService {
  /**
   * 获取所有订单项（分页+筛选+联表）
   * @param {number} page - 页码
   * @param {number} limit - 每页条数
   * @param {Object} filters - 筛选条件（orderId/productId）
   * @returns {Object} { orderItems: 订单项列表, pagination: 分页信息 }
   */
  async findAllOrderItems(page = 1, limit = 10, filters = {}) {
    try {
      const offset = (page - 1) * limit;
      const whereClause = {};

      // 按订单ID筛选
      if (filters.orderId) {
        whereClause.orderId = filters.orderId;
      }

      // 按产品ID筛选
      if (filters.productId) {
        whereClause.productId = filters.productId;
      }

      // 在 findAllOrderItems 方法中，修改 include 配置：
      const { count, rows } = await OrderItem.findAndCountAll({
        where: whereClause,
        include: [
          {
            model: Order,
            as: "order",
            attributes: [
              "id",
              "orderNumber",
              "status",
              "totalAmount",
              "paymentStatus",
            ],
            // 新增：关联订单所属用户（仅返回必要字段，避免冗余）
            include: [
              {
                model: User,
                as: "user",
                attributes: [
                  "id",
                  "username",
                  "email",
                  "firstName",
                  "lastName",
                ], // 只返回需要的用户字段
              },
            ],
          },
          {
            model: Product,
            as: "product",
            attributes: ["id", "name", "price", "image"],
          },
        ],
        order: [["createdAt", "DESC"]],
        limit: parseInt(limit),
        offset: offset,
      });

      return {
        orderItems: rows,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: count,
          pages: Math.ceil(count / limit),
        },
      };
    } catch (error) {
      throw new Error(`获取订单项列表失败: ${error.message}`);
    }
  }

  /**
   * 获取单个订单项详情（深度联表：订单+产品+用户）
   * @param {number/string} id - 订单项ID
   * @returns {Object} 订单项详情（含关联信息）
   */
  async findOrderItemById(id) {
    try {
      const orderItem = await OrderItem.findByPk(id, {
        include: [
          // 联表订单+用户（通过订单关联用户）
          {
            model: Order,
            as: "order",
            attributes: [
              "id",
              "orderNumber",
              "status",
              "paymentStatus",
              "createdAt",
            ],
            include: [
              {
                model: User,
                as: "user",
                attributes: [
                  "id",
                  "username",
                  "email",
                  "firstName",
                  "lastName",
                ], // 排除密码
              },
            ],
          },
          // 联表产品+分类（通过产品关联分类）
          {
            model: Product,
            as: "product",
            attributes: [
              "id",
              "name",
              "price",
              "originalPrice",
              "image",
              "stock",
            ],
            include: [
              {
                model: Category, // 关联产品分类
                as: "category",
                attributes: ["id", "name"],
              },
            ],
          },
        ],
      });

      if (!orderItem) {
        throw createError(404, "订单项不存在");
      }

      return orderItem;
    } catch (error) {
      if (error.status === 404) throw error;
      throw new Error(`获取订单项详情失败: ${error.message}`);
    }
  }

  /**
   * 创建订单项（含数据校验）
   * @param {Object} itemData - 订单项数据（orderId, productId, quantity, price）
   * @returns {Object} 新创建的订单项
   */
  async createOrderItem(itemData) {
    try {
      const { orderId, productId, quantity, price } = itemData;

      // 校验必要参数
      if (!orderId || !productId || !quantity || !price) {
        throw createError(
          400,
          "缺少必要参数：orderId/productId/quantity/price"
        );
      }

      // 校验订单是否存在
      const order = await Order.findByPk(orderId);
      if (!order) {
        throw createError(404, `关联的订单不存在：orderId=${orderId}`);
      }

      // 校验产品是否存在且状态正常
      const product = await Product.findByPk(productId);
      if (!product) {
        throw createError(404, `关联的产品不存在：productId=${productId}`);
      }
      if (product.status !== "active") {
        throw createError(
          400,
          `产品不可购买：${product.name}（状态：${product.status}）`
        );
      }

      // 校验库存是否充足
      if (product.stock < quantity) {
        throw createError(
          400,
          `产品库存不足：${product.name}（库存：${product.stock}，需求：${quantity}）`
        );
      }

      // 计算订单项总金额
      const total = price * quantity;

      // 创建订单项
      const orderItem = await OrderItem.create({
        orderId,
        productId,
        quantity,
        price,
        total,
        createdAt: new Date(),
        updatedAt: new Date(),
      });

      // 更新订单总金额（订单项变化后需同步订单金额）
      await this.updateOrderTotalAmount(orderId);

      return orderItem;
    } catch (error) {
      if (error.status) throw error;
      throw new Error(`创建订单项失败: ${error.message}`);
    }
  }

  /**
   * 更新订单项（仅允许修改数量、价格等字段）
   * @param {number/string} id - 订单项ID
   * @param {Object} updateData - 待更新数据（quantity/price）
   * @returns {Object} 更新后的订单项
   */
  async updateOrderItem(id, updateData) {
    try {
      const orderItem = await OrderItem.findByPk(id);
      if (!orderItem) {
        throw createError(404, "订单项不存在");
      }

      // 仅允许更新数量和价格（不允许修改关联的订单ID和产品ID）
      const { quantity, price } = updateData;
      let needUpdateTotal = false;

      // 验证并更新数量（需校验库存）
      if (quantity !== undefined && quantity !== orderItem.quantity) {
        const product = await Product.findByPk(orderItem.productId);
        if (product.stock < quantity) {
          throw createError(
            400,
            `产品库存不足：${product.name}（库存：${product.stock}，需求：${quantity}）`
          );
        }
        orderItem.quantity = quantity;
        needUpdateTotal = true;
      }

      // 更新价格
      if (price !== undefined && price !== orderItem.price) {
        orderItem.price = price;
        needUpdateTotal = true;
      }

      // 重新计算总金额（如果数量或价格有变化）
      if (needUpdateTotal) {
        orderItem.total = orderItem.price * orderItem.quantity;
      }

      // 保存更新
      await orderItem.save();

      // 同步更新订单总金额
      await this.updateOrderTotalAmount(orderItem.orderId);

      return orderItem;
    } catch (error) {
      if (error.status) throw error;
      throw new Error(`更新订单项失败: ${error.message}`);
    }
  }

  /**
   * 删除订单项
   * @param {number/string} id - 订单项ID
   * @returns {Object} 删除成功提示
   */
  async deleteOrderItem(id) {
    try {
      const orderItem = await OrderItem.findByPk(id);
      if (!orderItem) {
        throw createError(404, "订单项不存在");
      }

      // 记录关联的订单ID（用于后续更新订单总金额）
      const orderId = orderItem.orderId;

      // 删除订单项
      await orderItem.destroy();

      // 同步更新订单总金额
      await this.updateOrderTotalAmount(orderId);

      return { message: "订单项删除成功" };
    } catch (error) {
      if (error.status) throw error;
      throw new Error(`删除订单项失败: ${error.message}`);
    }
  }

  /**
   * 辅助方法：更新订单总金额（基于所有订单项的总和）
   * @param {number} orderId - 订单ID
   */
  async updateOrderTotalAmount(orderId) {
    // 查询该订单下所有订单项的总金额
    const result = await OrderItem.findOne({
      where: { orderId },
      attributes: [
        [sequelize.fn("SUM", sequelize.col("total")), "totalAmount"],
      ],
    });

    const totalAmount = result?.dataValues?.totalAmount || 0;

    // 更新订单的总金额
    await Order.update(
      { totalAmount, updatedAt: new Date() },
      { where: { id: orderId } }
    );
  }
}

module.exports = new OrderItemService();
